package com.example.knowman.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.knowman.ObService.*;
import com.example.knowman.ReturnMessage.Message;
import com.example.knowman.ReturnMessage.MessageBackKnowMainId;
import com.example.knowman.dao.knowLabelDetailAddLabels;
import com.example.knowman.dao.knowMainEx;
import com.example.knowman.dao.knowMainEx9_5ByPeriod;
import com.example.knowman.dao.knowMainExDaBiao;
import com.example.knowman.entity.*;
import com.example.knowman.mapper.KnowCategoryMapper;
import com.example.knowman.mapper.KnowMainMapper;
import com.example.knowman.mapper.StaffListMapper;

import com.example.knowman.service.IKnowCategoryService;
import com.example.knowman.service.IKnowShareService;
import com.example.knowman.service.IStaffListService;
import com.example.knowman.service.IKnowMainService;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

@Service
public class KnowMainServiceImpl extends ServiceImpl<KnowMainMapper, knowMain> implements IKnowMainService {

    private final KnowCategoryMapper knowCategoryMapper;

    private final IStaffListService iStaffListService;

    private final IKnowCategoryService iKnowCategoryService;

    private final OBknowArchFilesService oBknowArchFilesService;

    private final OBknowLabelMainService oBknowLabelMainService;

    private final OBknowLabelDetailService oBknowLabelDetailService;

    private final OBarchLabelMainService oBarchLabelMainService;

    private final OBarchLabelDetailService oBarchLabelDetailService;
    private final OBKnowCategoryService obKnowCategoryService;

    private final OBlabelCategoryService oBlabelCategoryService;

    private final IKnowShareService iKnowShareService;

    private final StaffListMapper staffListMapper;
    public KnowMainServiceImpl(KnowCategoryMapper knowCategoryMapper, IStaffListService iStaffListService,
                               StaffListMapper staffListMapper,IKnowCategoryService iKnowCategoryService,OBknowArchFilesService oBknowArchFilesService,
                               OBknowLabelMainService oBknowLabelMainService,OBknowLabelDetailService oBknowLabelDetailService,OBKnowCategoryService obKnowCategoryService,
                               OBarchLabelMainService oBarchLabelMainService,OBarchLabelDetailService oBarchLabelDetailService,OBlabelCategoryService oBlabelCategoryService,
                               IKnowShareService iKnowShareService) {
//        this.iTable1Service = iTable1Service;
        this.knowCategoryMapper = knowCategoryMapper;
        this.iStaffListService = iStaffListService;
        this.staffListMapper = staffListMapper;
        this.iKnowCategoryService = iKnowCategoryService;
        this.oBknowArchFilesService = oBknowArchFilesService;
        this.oBknowLabelMainService = oBknowLabelMainService;
        this.oBknowLabelDetailService = oBknowLabelDetailService;
        this.obKnowCategoryService = obKnowCategoryService;
        this.oBarchLabelMainService = oBarchLabelMainService;
        this.oBarchLabelDetailService = oBarchLabelDetailService;
        this.oBlabelCategoryService = oBlabelCategoryService;
        this.iKnowShareService = iKnowShareService;
    }




    @Override
    public Integer getCount(knowMainEx9_5ByPeriod temp, List<knowCategory> kcL, Integer timeType) {
        Integer sum = 0;
        String ttt = temp.getPeriod();
//        System.out.println(ttt);
//        String ttt = "2023";
        if(timeType == 1){
            for(knowCategory item: kcL){
                List<knowMain> t = this.lambdaQuery()
                        .eq(knowMain::getKnowCateId,item.getKnowCateId())
                        .eq(knowMain::getStaffCode,temp.getStaffCode())
                        .eq(knowMain::getKnowState,3)
                        .apply("YEAR(\"createtime\") = {0}", ttt)
                        .list();


                sum+=t.size();

            }
        }
        else if (timeType == 2){
            for(knowCategory item: kcL){
                List<knowMain> t = this.lambdaQuery()
                        .eq(knowMain::getKnowCateId,item.getKnowCateId())
                        .eq(knowMain::getStaffCode,temp.getStaffCode())
                        .eq(knowMain::getKnowState,3)
                        .apply("DATE_FORMAT(\"createtime\", '%Y-%m') = {0}", ttt)
                        .list();


                sum+=t.size();

            }
        }
        else if (timeType == 3){
            for(knowCategory item: kcL){
                List<knowMain> t = this.lambdaQuery()
                        .eq(knowMain::getKnowCateId,item.getKnowCateId())
                        .eq(knowMain::getStaffCode,temp.getStaffCode())
                        .eq(knowMain::getKnowState,3)
                        .apply("DATE_FORMAT(\"createtime\", '%Y-%m-%d') = {0}", ttt)
                        .list();


                sum+=t.size();

            }
        }
        else {
            for(knowCategory item: kcL){
                List<knowMain> t = this.lambdaQuery()
                        .eq(knowMain::getKnowCateId,item.getKnowCateId())
                        .eq(knowMain::getStaffCode,temp.getStaffCode())
                        .eq(knowMain::getKnowState,3)
                        .list();
                sum+=t.size();

            }
        }

//        System.out.println(sum);
        return sum;
    }

    @Override
    public IPage<knowMainEx> getAll(Integer pageNum, Integer pageSize, String knowTitle, String staffCode, Integer knowCateId, Integer readCount, Integer praiseCount, Integer commentCount, Integer knowState,String myStaffCode) {
        IPage<knowMainEx> Respage = new Page<>(pageNum, pageSize);
        List<knowMainEx> recordsL = new ArrayList<>();

        //返回knowCateId及所属小类
        List<knowCategory> knowCGs = obKnowCategoryService.getChilds(knowCateId);
        List<Integer> KCGs = new ArrayList<>();
        for (knowCategory item:knowCGs){
            KCGs.add(item.getKnowCateId());
        }

        IPage<knowMain> page = new Page<>(pageNum, pageSize);
        page = this.lambdaQuery().select()
                .like(knowTitle !=null && !knowTitle.isEmpty(),knowMain::getKnowTitle,knowTitle)
                .eq(staffCode !=null && !staffCode.isEmpty(),knowMain::getStaffCode,staffCode)
                .eq(knowCateId!=null,knowMain::getKnowCateId,knowCateId)
                .in(KCGs.size()>0 && KCGs!=null,knowMain::getKnowCateId,KCGs)
                .ge(readCount!=null,knowMain::getReadCount,readCount)
                .ge(praiseCount!=null,knowMain::getPraiseCount,praiseCount)
                .ge(commentCount!=null,knowMain::getCommentCount,commentCount)
                .eq(knowState!=null,knowMain::getKnowState,knowState)
                .orderByDesc(knowMain::getCreatetime)
                .page(page);

//        Map<String,String> SL = iStaffListService.getIdAndName();
        Map<String, staffList> SLs = iStaffListService.getAll();
        Map<Integer,String> KCL = iKnowCategoryService.getIdAndName();



        for (knowMain item:page.getRecords()){
            knowMainEx temp = new knowMainEx();

            temp.setKnowId(item.getKnowId());
            temp.setKnowTitle(item.getKnowTitle());
            temp.setKnowContent(item.getKnowContent());
            temp.setKnowCateId(item.getKnowCateId());
            temp.setKnowCateName(KCL.get(item.getKnowCateId()));
            temp.setStaffCode(item.getStaffCode());
            temp.setStaffName(SLs.get(item.getStaffCode()).getStaffName());
            if(item.getAuditUser()!=null && !item.getAuditUser().isEmpty()){
                temp.setAuditUser(item.getAuditUser());
                temp.setAduitUserName(SLs.get(item.getAuditUser()).getStaffName());
            }
            temp.setKnowState(item.getKnowState());
            temp.setReadCount(item.getReadCount());
            temp.setPraiseCount(item.getPraiseCount());
            temp.setCommentCount(item.getCommentCount());
            temp.setCreatetime(item.getCreatetime());
            temp.setArchDeptName(SLs.get(item.getStaffCode()).getArchDeptName());




            recordsL.add(temp);
        }

        //判断是否在knowShare中有数据
        if(myStaffCode !=null && !myStaffCode.isEmpty()){
            List<knowShare> Bks = iKnowShareService.getByMyStaffCode(myStaffCode);
            for (knowMainEx item:recordsL){
                boolean flag = false;
                for (knowShare check:Bks){
                    if(item.getKnowId() == check.getKnowId()){
                        flag = true;
                    }
                }
                item.setKS_in(flag);
            }
        }

        Respage.setRecords(recordsL);
        Respage.setTotal(page.getTotal());
        return Respage;
    }

    @Override
    public knowMainExDaBiao getByKnowId(Integer knowId) {
//        knowMainEx Respage = new knowMainEx();
        knowMain item = this.lambdaQuery().select().eq(knowMain::getKnowId,knowId).one();

        Map<String,String> SL = iStaffListService.getIdAndName();
        Map<Integer,String> KCL = iKnowCategoryService.getIdAndName();

        knowLabelMain KLM = oBknowLabelMainService.getSingle(knowId);
        List<knowLabelDetail> KLDs = oBknowLabelDetailService.Dabiaos(KLM.getKnowLblId());

        knowMainExDaBiao temp = new knowMainExDaBiao();

        temp.setKnowId(item.getKnowId());
        temp.setKnowTitle(item.getKnowTitle());
        temp.setKnowContent(item.getKnowContent());
//        temp.setKnowCateId(item.getKnowCateId());
        temp.setKnowCateName(KCL.get(item.getKnowCateId()));
//        temp.setStaffCode(item.getStaffCode());
//        temp.setStaffName(SL.get(item.getStaffCode()));
//        temp.setAuditUser(item.getAuditUser());
//        temp.setAduitUserName(SL.get(item.getAuditUser()));
        temp.setKnowState(item.getKnowState());
//        temp.setReadCount(item.getReadCount());
//        temp.setPraiseCount(item.getPraiseCount());
//        temp.setCommentCount(item.getCommentCount());
//        temp.setCreatetime(item.getCreatetime());

//        temp.setItemMain(KLM);
//        temp.setItemDetails(KLDs);

        temp.setDaBiaoContent(KLM.getLblContent());

        //打标详情+标签
        Map<Integer,labelCategory> LCList = oBlabelCategoryService.getLabelDetails();
        List<knowLabelDetailAddLabels> det =new ArrayList<>();
        for(knowLabelDetail it:KLDs){
            knowLabelDetailAddLabels t = new knowLabelDetailAddLabels();
            t.setLblContent(it.getLblContent());
            t.setKnowLblDtlId(it.getKnowLblDtlId());
            t.setLabelColor(LCList.get(it.getLabelCateId()).getLabelColor());
            t.setLabelName(LCList.get(it.getLabelCateId()).getLabelName());

            det.add(t);
        }

        temp.setItemDetails(det);
        return temp;
    }

    @Override
    public Message check(Integer knowId) {
        Message message = new Message();

        //获取已通过的知识，用于标题查重
        List<knowMain> lis = this.lambdaQuery().select().eq(knowMain::getKnowState,3).list();
        knowMain item = this.lambdaQuery().select().eq(knowMain::getKnowId,knowId).one();

        if(item.getKnowState()!=0){
            message.setCode(100);
            message.setTip("该知识状态不可进行审核");
            return message;
        }

        for(knowMain it:lis){
            if(it.getKnowTitle().equals(item.getKnowTitle())){
                message.setCode(200);
                message.setTip("形式审查未通过");

                //将状态改为1
                this.lambdaUpdate().eq(knowMain::getKnowId,knowId)
                        .set(knowMain::getKnowState,1).update();
                return message;
            }
        }
        //


        //形式审查通过
        message.setCode(200);
        message.setTip("形式审查通过,可打标");

        //将状态改为4
        this.lambdaUpdate().eq(knowMain::getKnowId,knowId)
                .set(knowMain::getKnowState,4).update();

        return message;
        //

    }

    @Override
    public Message updateExceptSC(Integer knowId, String knowTitle, String knowContent, Integer knowCateId, String auditUser, Integer knowState, Integer readCount, Integer praiseCount, Integer commentCount) {
        Message message = new Message();

        //对知识标题和内容的修改进行限制，如果已经打标则不能修改
        if(knowTitle!=null || knowContent!=null){
            knowLabelMain temp = oBknowLabelMainService.getSingle(knowId);
            archLabelMain temp2 = oBarchLabelMainService.getSingle(knowId);
            if(temp2==null){
                Integer NumKLD = oBknowLabelDetailService.backByknowLblId(temp.getKnowLblId());
                if(NumKLD != 0 ){
                    message.setCode(100);
                    message.setTip("该知识已打标，不可对标题或内容进行修改！");
                    return message;
                }
            }
            if(temp == null){
                Integer NumALD = oBarchLabelDetailService.backByarchLblId(temp2.getArchLblId());
                if( NumALD!=0){
                    message.setCode(100);
                    message.setTip("该知识已打标，不可对标题或内容进行修改！");
                    return message;
                }
            }

        }

        //


        this.lambdaUpdate().eq(knowMain::getKnowId,knowId)
                .set(knowTitle != null && !knowTitle.isEmpty(),knowMain::getKnowTitle,knowTitle)
                .set(knowContent != null && !knowContent.isEmpty(),knowMain::getKnowContent,knowContent)
                .set(knowCateId != null,knowMain::getKnowCateId,knowCateId)
                .set(auditUser != null && !auditUser.isEmpty(),knowMain::getAuditUser,auditUser)
                .set(knowState != null,knowMain::getKnowState,knowState)
                .set(readCount != null,knowMain::getReadCount,readCount)
                .set(praiseCount != null,knowMain::getPraiseCount,praiseCount)
                .set(commentCount != null,knowMain::getCommentCount,commentCount)
                .update();

        message.setCode(200);
        message.setTip("修改成功");

        return message;
    }

    @Override
    public Message deleteByknowId(Integer knowId) {
        Message message = new Message();
        knowMain check = this.lambdaQuery().select().eq(knowMain::getKnowId,knowId).one();
        if(check.getKnowState() == 3){
            message.setCode(100);
            message.setTip("删除失败,该知识已审核通过！");
            return message;
        }


        //删除knowArchFiles关联数据(knowId)
        oBknowArchFilesService.deleteByKnowId(knowId);
        //删除knowLabelDetail关联数据，需要先得到knowLabelMain对应knowId的数据的knowLblDtlId
        knowLabelMain temp = oBknowLabelMainService.getSingle(knowId);
        if(temp!=null){
            oBknowLabelDetailService.deleteByknowLblId(temp.getKnowLblId());
        }

        //删除knowLabelMain关联数据
        oBknowLabelMainService.deleteByKnowId(knowId);

//        //删除archLabelMain与archLabelDetail关联数据
//        archLabelMain temp2 = oBarchLabelMainService.getSingle(knowId);
//        if(temp2!=null){
//            oBarchLabelDetailService.deleteByarchLblId(temp2.getArchLblId());
//        }
//
//        oBarchLabelMainService.deleteByKnowId(knowId);

        QueryWrapper<knowMain> wrapper = new QueryWrapper<>();
        wrapper.eq("\"knowId\"",knowId);
        try{
            this.remove(wrapper);
            message.setCode(200);
            message.setTip("删除成功");
        }catch (Exception e){
            message.setCode(100);
            message.setTip("删除失败");
        }

        return message;
    }

    @Override
    public List<knowMain> getForSum(Integer timeType, String period) {
        String ttt = period;
        List<knowMain> t = new ArrayList<>();
//        System.out.println(ttt);
//        String ttt = "2023";
        if(timeType == 1){
            t = this.lambdaQuery()
                .eq(knowMain::getKnowState,3)
                .apply("YEAR(\"createtime\") = {0}", ttt)
                .list();
        }
        else if (timeType == 2){
                t = this.lambdaQuery()
                        .eq(knowMain::getKnowState,3)
                        .apply("DATE_FORMAT(\"createtime\", '%Y-%m') = {0}", ttt)
                        .list();
        }
        else if (timeType == 3){

                t = this.lambdaQuery()
                        .eq(knowMain::getKnowState,3)
                        .apply("DATE_FORMAT(\"createtime\", '%Y-%m-%d') = {0}", ttt)
                        .list();
        }
        else {

                t = this.lambdaQuery()
                        .eq(knowMain::getKnowState,3)
                        .list();
        }

//        System.out.println(sum);
        return t;
    }

    @Override
    public IPage<knowMainEx> getAuditsKM(Integer pageNum, Integer pageSize, String knowTitle, String auditUser,Integer knowState, List<staffList> MSL) {
        IPage<knowMainEx> Respage = new Page<>(pageNum, pageSize);
        List<knowMainEx> recordsL = new ArrayList<>();

        //从archDept表找到是哪个部门主管以及该部门信息（archDeptCode）
        //得到部门所有的员工
        //得到员工们发布的知识，2审核不通过/3审核通过/5打标完成待审核

        List<Integer> stateShow = new ArrayList<>(Arrays.asList(2, 3, 5));

        List<String> SLcode = new ArrayList<>();
        for (staffList item:MSL){
            SLcode.add(item.getStaffCode());
        }

        IPage<knowMain> page = new Page<>(pageNum, pageSize);
        page = this.lambdaQuery().select()
                .like(knowTitle !=null && !knowTitle.isEmpty(),knowMain::getKnowTitle,knowTitle)
//                .eq(auditUser !=null && !auditUser.isEmpty(),knowMain::getAuditUser,auditUser)
                .in(knowMain::getStaffCode,SLcode)
                .in(knowMain::getKnowState,stateShow)
                .eq(knowState!=null,knowMain::getKnowState,knowState)
                .page(page);

        Map<String,String> SL = iStaffListService.getIdAndName();
        Map<Integer,String> KCL = iKnowCategoryService.getIdAndName();

        for (knowMain item:page.getRecords()){
            knowMainEx temp = new knowMainEx();

            temp.setKnowId(item.getKnowId());
            temp.setKnowTitle(item.getKnowTitle());
            temp.setKnowContent(item.getKnowContent());
            temp.setKnowCateId(item.getKnowCateId());
            temp.setKnowCateName(KCL.get(item.getKnowCateId()));
            temp.setStaffCode(item.getStaffCode());
            temp.setStaffName(SL.get(item.getStaffCode()));
            temp.setAuditUser(item.getAuditUser());
            temp.setAduitUserName(SL.get(item.getAuditUser()));
            temp.setKnowState(item.getKnowState());
            temp.setReadCount(item.getReadCount());
            temp.setPraiseCount(item.getPraiseCount());
            temp.setCommentCount(item.getCommentCount());
            temp.setCreatetime(item.getCreatetime());

            recordsL.add(temp);
        }

        recordsL.sort((o1, o2) -> o2.getKnowState().compareTo(o1.getKnowState()));
        Respage.setRecords(recordsL);
        Respage.setTotal(page.getTotal());
        return Respage;
    }


    @Override
    public MessageBackKnowMainId Insert(String knowTitle, String knowContent, Integer knowCateId, String staffCode, String auditUser) {

        MessageBackKnowMainId message = new MessageBackKnowMainId();

        knowMain temp = new knowMain();
        temp.setKnowTitle(knowTitle);
        temp.setKnowContent(knowContent);
        temp.setKnowCateId(knowCateId);
        temp.setStaffCode(staffCode);
        temp.setAuditUser(auditUser);
        temp.setReadCount(0);
        temp.setPraiseCount(0);
        temp.setCommentCount(0);

//        knowMain check = this.lambdaQuery().select().eq(knowMain::getStaffCode,staffCode)
//                .eq(auditUser !=null && !auditUser.isEmpty(),knowMain::getAuditUser,auditUser)
//                .eq(knowTitle !=null && !knowTitle.isEmpty(), knowMain::getKnowTitle,knowTitle)
//                .eq(knowContent !=null && !knowContent.isEmpty(), knowMain::getKnowContent,knowContent)
//                .eq(knowCateId !=null, knowMain::getKnowCateId,knowCateId)
//                .orderByDesc(knowMain::getCreatetime).one();
//        if(check!=null){
//            message.setCode(100);
//            message.setTip("新增失败,已存在该数据");
//            return message;
//        }


        try{
            this.save(temp);
            List<knowMain> insertedRecord = this.lambdaQuery().select().eq(knowMain::getStaffCode,staffCode)
                    .eq(auditUser !=null && !auditUser.isEmpty(),knowMain::getAuditUser,auditUser)
                    .eq(knowTitle !=null && !knowTitle.isEmpty(), knowMain::getKnowTitle,knowTitle)
                    .eq(knowContent !=null && !knowContent.isEmpty(), knowMain::getKnowContent,knowContent)
                    .orderByDesc(knowMain::getCreatetime).list();
            System.out.println(insertedRecord);
            message.setCode(200);
            message.setTip("新增成功");
            message.setKnowId(insertedRecord.get(0).getKnowId()); // 获取并设置knowId

        }catch (Exception e){
            message.setCode(100);
            message.setTip("新增失败");
        }

        return message;
    }


}
